package com.example.iceserverdemo.meeting.components;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.iceserverdemo.meeting.services.MeetingService;
import lombok.var;
import org.springframework.stereotype.Component;
import person.jianglong.common.utils.LogUtil;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

/**
 * 测试工具 http://www.websocket-test.com/
 */
@Component
@ServerEndpoint("/ice")
public class MeetingSocket {
    @OnOpen
    public void onOpen(Session session) throws Exception {
        LogUtil.info("连接成功,session.ID:{}", session.getId());
        var data = new JSONObject();
        data.put("type", "open");
        data.put("session", session.getId());
        MeetingService.sendMessageTo(session, data.toString());
        MeetingService.addSession(session);
    }

    @OnMessage
    public void onMessage(Session session, String message) throws Exception {
        //LogUtil.info("收到消息,session.ID:{},message:{}", session.getId(), message);//太多了 不打了
        var data = JSONUtil.parseObj(message);
        data.put("session", session.getId());

        if (data.containsKey("target")) {
            MeetingService.sendMessageTo(data.getStr("target"), data.toString());
            return;
        }

        if (data.containsKey("targets")) {
            MeetingService.sendMessageTo(data.get("targets", String[].class), data.toString());
            return;
        }

        MeetingService.sendMessageExcept(session, data.toString());
    }

    @OnClose
    public void onClose(Session session) throws Exception {
        LogUtil.info("连接关闭,session.ID:{}", session.getId());
        var sessionId = session.getId();
        var data = new JSONObject();
        data.put("type", "close");
        data.put("session", sessionId);
        MeetingService.sendMessageExcept(session, data.toString());
        MeetingService.removeSession(session);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        LogUtil.info("会话异常,session.ID:{},error:{}", session.getId(), throwable.getMessage());
    }
}
